﻿using AutoMapper;
using BW.MesProject.Public.Domain.RBAC;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using BW.MesProject.WareHouse.Infrastructure;
using BW.MesProject.WareHouse.Infrastructure.Dto.Input;
using BW.MesProject.WareHouse.Infrastructure.Dto.OutPut;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.WareHouse.Application
{
    /// <summary>
    /// 审批流程
    /// </summary>
    public class ProcessNodeNewServices : IProcessNodeServices
    {
        private readonly IBaseRepository<ProcessNodes> _ProcessNodes;//审批流程主单
        private readonly IBaseRepository<ProcessNodesItem> _ProcessNodesItem;//审批流程明细
        private readonly IBaseRepository<ProcessRecords> _ProcessRecords;//审批流程记录表
        private readonly IBaseRepository<ApprovalProcess> _ApprovalProcess;//审批表
        private readonly IBaseRepository<UserModel> _userModel;//用户表
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ProcessNodes">审批流程主单</param>
        /// <param name="ProcessRecords">审批流程记录表</param>
        /// <param name="ProcessNodesItem">审批流程明细</param>
        /// <param name="ApprovalProcess">审批表</param>
        /// /// <param name="UserModel">用户表</param>
        /// <param name="mapper"></param>
        public ProcessNodeNewServices(IBaseRepository<ProcessNodes> ProcessNodes,
                               IBaseRepository<ProcessRecords> ProcessRecords,
                               IBaseRepository<ProcessNodesItem> ProcessNodesItem,
                               IBaseRepository<ApprovalProcess> ApprovalProcess,
                               IBaseRepository<UserModel> UserModel,
                               IMapper mapper)
        {
            _ProcessNodes = ProcessNodes;
            _ProcessRecords = ProcessRecords;
            _ProcessNodesItem = ProcessNodesItem;
            _ApprovalProcess = ApprovalProcess;
            _userModel = UserModel;
            this._mapper = mapper;
        }

        #region 添加
        /// <summary>
        /// 添加审批流程节点主表,审批流程节点明细
        /// </summary>
        /// <param name="processNodeInput"></param>
        /// <returns></returns>
        public ApiResult<int> AddProcessNodes(ProcessNodeInput processNodeInput)
        {
            try
            {
                //判断审批流程编码，名称是否为空
                if (string.IsNullOrEmpty(processNodeInput.ProcessNodes.ProcessNodesId) || string.IsNullOrEmpty(processNodeInput.ProcessNodes.ProcessNodesName))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "请检查审批流程编码，名称是否为空"
                    };
                }
                var model = _ProcessNodes.GetValue(x => x.ProcessNodesId == processNodeInput.ProcessNodes.ProcessNodesId);
                if (model != null && !string.IsNullOrEmpty(model.ProcessNodesId))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "审批流程编号重复，请重新检查修改！！！"
                    };
                }

                // 获取数据库上下文，用于事务处理
                var db = _ProcessNodes.GetAll().Context;

                try
                {
                    // 开始事务
                    db.Ado.BeginTran();

                    // 添加审批流程节点主表
                    var mainResult = _ProcessNodes.Add(processNodeInput.ProcessNodes);
                    if (mainResult <= 0)
                    {
                        throw new Exception("添加审批流程节点主表失败");
                    }

                    // 添加审批流程节点明细
                    if (processNodeInput.ProcessNodesItem != null && processNodeInput.ProcessNodesItem.Any())
                    {
                        foreach (var item in processNodeInput.ProcessNodesItem)
                        {
                            // 确保关联正确
                            item.ProcessNodesId = processNodeInput.ProcessNodes.ProcessNodesId;

                            // 验证明细项
                            if (string.IsNullOrEmpty(item.ProcessNodesItemId) || string.IsNullOrEmpty(item.NodeName))
                            {
                                throw new Exception("审批流程节点明细编码或名称不能为空");
                            }

                            var existingItem = _ProcessNodesItem.GetValue(x => x.ProcessNodesItemId == item.ProcessNodesItemId);
                            if (existingItem != null && !string.IsNullOrEmpty(existingItem.ProcessNodesItemId))
                            {
                                throw new Exception($"审批流程节点明细编号 {item.ProcessNodesItemId} 重复，请检查修改");
                            }

                            var itemResult = _ProcessNodesItem.Add(item);
                            if (itemResult <= 0)
                            {
                                throw new Exception($"添加审批流程节点明细失败");
                            }
                        }
                    }

                    // 提交事务
                    db.Ado.CommitTran();

                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Success,
                        Message = "添加成功",
                        Data = mainResult,
                        TotalCount = 0
                    };
                }
                catch (Exception ex)
                {
                    // 回滚事务
                    db.Ado.RollbackTran();
                    throw;
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"添加审批流程时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"添加失败: {ex.Message}",
                    Data = 0,
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 添加审批表\审批流程记录表
        /// </summary>
        /// <param name="approvalProcess"></param>
        /// <returns></returns>
        public ApiResult<bool> AddApproveProcess(ApprovalProcess approvalProcess)
        {
            try
            {
                //判断审批流程编码，名称是否为空
                if (string.IsNullOrEmpty(approvalProcess.ApprovalProcessId) || string.IsNullOrEmpty(approvalProcess.RequisitionId))
                {
                    return new ApiResult<bool>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "请检查审批编码和审批申请单的编码是否为空"
                    };
                }
                var model = _ApprovalProcess.GetValue(x => x.ApprovalProcessId == approvalProcess.ApprovalProcessId);
                if (model != null && !string.IsNullOrEmpty(model.ApprovalProcessId))
                {
                    return new ApiResult<bool>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "审批编号重复，请联系管理员！！！"
                    };
                }

                // 获取数据库上下文，用于事务处理
                var db = _ApprovalProcess.GetAll().Context;

                try
                {
                    // 开始事务
                    db.Ado.BeginTran();

                    // 添加审批表
                    var mainResult = _ApprovalProcess.Add(approvalProcess);
                    if (mainResult <= 0)
                    {
                        throw new Exception("添加审批表失败");
                    }

                    // 添加审批记录表
                    if (approvalProcess.ApprovalProcessId != null )
                    {
                        ProcessRecords processRecords=new ProcessRecords();
                        processRecords.ProcessRecordsId = YitIdHelper.NextId();
                        processRecords.ApprovalProcessId = approvalProcess.ApprovalProcessId;
                        processRecords.CurrentNode=approvalProcess.NodeName;
                        processRecords.CurrentNodeSn = approvalProcess.NodeSN;
                        processRecords.OperatorId = approvalProcess.OperatorId;
                        processRecords.Operator=approvalProcess.Operator;
                        processRecords.UpdateTime = approvalProcess.UpdateTime;
                        processRecords.IsRead = true;
                        processRecords.Ispass = approvalProcess.WFStatus;
                        processRecords.ApproveOpinion = approvalProcess.Memo;

                        var existingItem = _ProcessRecords.GetValue(x => x.ProcessRecordsId == processRecords.ProcessRecordsId);
                        if (existingItem != null && !string.IsNullOrEmpty(existingItem.ProcessRecordsId.ToString()))
                        {
                            throw new Exception($"审批记录编号 {processRecords.ProcessRecordsId} 重复，请检查修改");
                        }

                        var itemResult = _ProcessRecords.Add(processRecords);
                        if (itemResult <= 0)
                        {
                            throw new Exception($"添加审批记录失败");
                        }
                    }

                    // 提交事务
                    db.Ado.CommitTran();

                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Success,
                        Message = "添加成功",
                        Data = true,
                        TotalCount = 0
                    };
                }
                catch (Exception ex)
                {
                    // 回滚事务
                    db.Ado.RollbackTran();
                    throw;
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"添加审批时发生异常: {ex.Message}");

                return new ApiResult<bool>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"添加失败: {ex.Message}",
                    Data = false,
                    TotalCount = 0
                };
            }
        }

        #endregion

        #region 查询

        /// <summary>
        /// 获取审批流程列表（分页）
        /// </summary>
        /// <param name="qryInput"></param>
        /// <param name="PNType"></param>
        /// <returns></returns>
        public ApiResult<List<ProcessNodesOut>> GetProcessNodesList(QryInput qryInput,string PNType=null)
        {
            try
            {
                var query = _ProcessNodes.GetAll();

                // 条件筛选
                if (!string.IsNullOrEmpty(qryInput.QryID))
                {
                    query = query.Where(x => x.ProcessNodesId.Contains(qryInput.QryID));
                }
                if (!string.IsNullOrEmpty(qryInput.QryName))
                {
                    query = query.Where(x => x.ProcessNodesName.Contains(qryInput.QryName));
                }
                
                // 联表查询设备类型，获取设备类型名称等信息
                var query1 = query.LeftJoin<UserModel>((a, b) => a.CreateBy == b.UserId).Select((a, b) =>
                     new ProcessNodesOut
                     {
                         ProcessNodesId = a.ProcessNodesId,
                         ProcessNodesName = a.ProcessNodesName,
                         ProcessNodesType = a.ProcessNodesType,
                         CreateBy = b.UserId,
                         CreateByName = b.UserName,
                         CreateTime = a.CreateTime
                     });
                // 计算总数
                int totalCount = query1.Count();
                // 分页处理
                var data = query1.OrderByDescending(x => x.CreateTime)
                                .Skip((qryInput.PageNum - 1) * qryInput.PageSize)
                                .Take(qryInput.PageSize)
                                .ToList();

                return new ApiResult<List<ProcessNodesOut>>
                {
                    Code = ApiEnums.Success,
                    Message = "获取成功",
                    Data = data,
                    TotalCount = totalCount
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取审批流程节点列表时发生异常: {ex.Message}");
                return new ApiResult<List<ProcessNodesOut>>
                {
                    Code = ApiEnums.Fail,
                    Message = $"获取失败: {ex.Message}",
                    Data = null
                };
            }
        }


        /// <summary>
        /// 获取指定流程节点的明细列表
        /// </summary>
        /// <param name="processNodesId">流程节点ID</param>
        /// <returns>流程节点明细列表</returns>
        public ApiResult<List<ProcessNodesItem>> GetProcessNodesItemsByNodeId(string processNodesId)
        {
            try
            {
                if (string.IsNullOrEmpty(processNodesId))
                {
                    return new ApiResult<List<ProcessNodesItem>>
                    {
                        Code = ApiEnums.Fail,
                        Message = "流程节点ID不能为空",
                        Data = null
                    };
                }

                var items = _ProcessNodesItem.GetAll()
                                          .Where(x => x.ProcessNodesId == processNodesId)
                                          .OrderBy(x => x.NodeSn)
                                          .ToList();

                return new ApiResult<List<ProcessNodesItem>>
                {
                    Code = ApiEnums.Success,
                    Message = "获取成功",
                    Data = items,
                    TotalCount = items.Count
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取流程节点明细列表时发生异常: {ex.Message}");
                return new ApiResult<List<ProcessNodesItem>>
                {
                    Code = ApiEnums.Fail,
                    Message = $"获取失败: {ex.Message}",
                    Data = null
                };
            }
        }


        /// <summary>
        /// 获取单个流程节点明细
        /// </summary>
        /// <param name="NodeSn">节点ID</param>
        /// <returns>流程节点明细信息</returns>
        public ApiResult<ProcessNodesItem> GetProcessNodesItemById(string NodeSn)
        {
            try
            {
                if (string.IsNullOrEmpty(NodeSn))
                {
                    return new ApiResult<ProcessNodesItem>
                    {
                        Code = ApiEnums.Fail,
                        Message = "节点ID不能为空",
                        Data = null
                    };
                }

                var item = _ProcessNodesItem.GetValue(x => x.NodeSn == NodeSn);
                if (item == null)
                {
                    return new ApiResult<ProcessNodesItem>
                    {
                        Code = ApiEnums.Fail,
                        Message = "未找到指定的流程节点明细",
                        Data = null
                    };
                }

                return new ApiResult<ProcessNodesItem>
                {
                    Code = ApiEnums.Success,
                    Message = "获取成功",
                    Data = item
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取流程节点明细时发生异常: {ex.Message}");
                return new ApiResult<ProcessNodesItem>
                {
                    Code = ApiEnums.Fail,
                    Message = $"获取失败: {ex.Message}",
                    Data = null
                };
            }
        }


        /// <summary>
        /// 获取审批流程列表（分页）
        /// </summary>
        /// <param name="qryInput"></param>
        /// <param name="UserID">用户</param>
        /// <returns>审批流程列表</returns>
        public ApiResult<List<ApprovalProcess>> GetApprovalProcessList(QryInput qryInput, string UserID)
        {
            try
            {
                if (string.IsNullOrEmpty(UserID))
                {
                    return new ApiResult<List<ApprovalProcess>>
                    {
                        Code = ApiEnums.Fail,
                        Message = "用户不能为空",
                        Data = null
                    };
                }

                var userModel = _userModel.GetAll().Where(x => x.UserId == UserID)?.ToList();
                if (userModel==null) {
                    return new ApiResult<List<ApprovalProcess>>
                    {
                        Code = ApiEnums.Fail,
                        Message = "未找到用户信息",
                        Data = null
                    };
                }
                var query = _ApprovalProcess.GetAll();
                if (userModel[0].JobCode!= "J25070400026")
                {
                    query= query.Where(x => x.ToDoerId == UserID);
                }
                // 条件筛选
                if (!string.IsNullOrEmpty(qryInput.QryID))
                {
                    //long ApprovalProcessId = long.Parse(qryInput.QryID);
                    query = query.Where(x => x.ApprovalProcessId == qryInput.QryID);
                }

                // 条件筛选
                if (!string.IsNullOrEmpty(qryInput.QryName))
                {
                    query = query.Where(x => x.RequisitionId == qryInput.QryName);
                }

                // 计算总数
                int totalCount = query.Count();

                // 分页处理
                var data = query.OrderByDescending(x => x.CreateTime)
                                .Skip((qryInput.PageNum - 1) * qryInput.PageSize)
                                .Take(qryInput.PageSize)
                                .ToList();

                return new ApiResult<List<ApprovalProcess>>
                {
                    Code = ApiEnums.Success,
                    Message = "获取成功",
                    Data = data,
                    TotalCount = totalCount
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取审批流程列表时发生异常: {ex.Message}");
                return new ApiResult<List<ApprovalProcess>>
                {
                    Code = ApiEnums.Fail,
                    Message = $"获取失败: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取审批流程列表（分页）
        /// </summary>
        /// <param name="qryInput"></param>
        /// <param name="RequisitionId">申请单ID</param>
        /// <returns>审批流程列表</returns>
        public ApiResult<List<ApprovalProcess>> GetApprovalProcessByRId(string RequisitionId)
        {
            try
            {
                if (string.IsNullOrEmpty(RequisitionId))
                {
                    return new ApiResult<List<ApprovalProcess>>
                    {
                        Code = ApiEnums.Fail,
                        Message = "申请单编码不能为空，请检查！！！",
                        Data = null
                    };
                }

               
                var query = _ApprovalProcess.GetAll().Where(x => x.RequisitionId == RequisitionId).OrderByDescending(x => x.CreateTime)
                                .ToList();
                return new ApiResult<List<ApprovalProcess>>
                {
                    Code = ApiEnums.Success,
                    Message = "获取成功",
                    Data = query
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取审批流程列表时发生异常: {ex.Message}");
                return new ApiResult<List<ApprovalProcess>>
                {
                    Code = ApiEnums.Fail,
                    Message = $"获取失败: {ex.Message}",
                    Data = null
                };
            }
        }


        /// <summary>
        /// 获取审批流程的所有审批记录
        /// </summary>
        /// <param name="qryInput"></param>
        /// <param name="ApprovalProcessId">申请单ID</param>
        /// <returns></returns>
        public ApiResult<List<ProcessRecords>> GetProcessRecordsByProcessId(QryInput qryInput,string ApprovalProcessId)
        {
            try
            {
                if (string.IsNullOrEmpty(ApprovalProcessId))
                {
                    return new ApiResult<List<ProcessRecords>>
                    {
                        Code = ApiEnums.Fail,
                        Message = "审批流程ID不能为空",
                        Data = null
                    };
                }

                var records = _ProcessRecords.GetAll()
                                          .Where(x => x.ApprovalProcessId == ApprovalProcessId)
                                          .OrderBy(x => x.UpdateTime)
                                          .ToList();

                return new ApiResult<List<ProcessRecords>>
                {
                    Code = ApiEnums.Success,
                    Message = "获取成功",
                    Data = records,
                    TotalCount = records.Count
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取审批记录列表时发生异常: {ex.Message}");
                return new ApiResult<List<ProcessRecords>>
                {
                    Code = ApiEnums.Fail,
                    Message = $"获取失败: {ex.Message}",
                    Data = null
                };
            }
        }


        #endregion

        #region 修改

        /// <summary>
        /// 修改审批流程节点主表及明细信息
        /// </summary>
        /// <param name="processNodeInput">流程节点信息</param>
        /// <returns>操作结果</returns>
        public ApiResult<bool> UpdateProcessNodes(ProcessNodeInput processNodeInput)
        {
            try
            {
                // 参数验证
                if (processNodeInput == null || processNodeInput.ProcessNodes == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "流程节点信息不能为空",
                        Data = false
                    };
                }

                if (string.IsNullOrEmpty(processNodeInput.ProcessNodes.ProcessNodesId))
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "流程节点ID不能为空",
                        Data = false
                    };
                }
                //var approvalProcess = _ApprovalProcess.GetAll().Where(x => x.ProcessNodesId == processNodeInput.ProcessNodes.ProcessNodesId && (x.WFStatus==0 || x.WFStatus == 1 ))?.ToList();
                var approvalProcess = _ApprovalProcess.GetAll().Where(x => x.ProcessNodesId == processNodeInput.ProcessNodes.ProcessNodesId)?.ToList();
                if (approvalProcess.Count()>0)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "还有未完成的审批流程，完成流程后请停用该审批重新新建审批流程！！！",
                        Data = false
                    };

                }
                // 检查记录是否存在
                var existingNode = _ProcessNodes.GetValue(x => x.ProcessNodesId == processNodeInput.ProcessNodes.ProcessNodesId);
                if (existingNode == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = $"未找到ID为 {processNodeInput.ProcessNodes.ProcessNodesId} 的流程节点",
                        Data = false
                    };
                }

                // 获取数据库上下文，用于事务处理
                var db = _ProcessNodes.GetAll().Context;

                try
                {
                    // 开始事务
                    db.Ado.BeginTran();

                    // 更新审批流程节点主表
                    var mainResult = _ProcessNodes.Update(processNodeInput.ProcessNodes);
                    if (mainResult <= 0)
                    {
                        throw new Exception("更新审批流程节点主表失败");
                    }

                    // 处理审批流程节点明细
                    if (processNodeInput.ProcessNodesItem != null && processNodeInput.ProcessNodesItem.Any())
                    {
                        // 先删除旧的明细记录
                        var existingItems = _ProcessNodesItem.GetAll().Where(x => x.ProcessNodesId == processNodeInput.ProcessNodes.ProcessNodesId).ToList();
                        foreach (var item in existingItems)
                        {
                            var deleteResult = _ProcessNodesItem.Delete(item);
                            if (deleteResult <= 0)
                            {
                                throw new Exception($"删除原流程节点明细失败: {item.ProcessNodesItemId}");
                            }
                        }

                        // 添加新的明细记录
                        foreach (var item in processNodeInput.ProcessNodesItem)
                        {
                            // 确保关联正确
                            item.ProcessNodesId = processNodeInput.ProcessNodes.ProcessNodesId;

                            // 验证明细项
                            if (string.IsNullOrEmpty(item.ProcessNodesItemId) || string.IsNullOrEmpty(item.NodeName))
                            {
                                throw new Exception("审批流程节点明细编码或名称不能为空");
                            }

                            var itemResult = _ProcessNodesItem.Add(item);
                            if (itemResult <= 0)
                            {
                                throw new Exception($"添加流程节点明细失败");
                            }
                        }
                    }

                    // 提交事务
                    db.Ado.CommitTran();

                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Success,
                        Message = "修改成功",
                        Data = true
                    };
                }
                catch (Exception ex)
                {
                    // 回滚事务
                    db.Ado.RollbackTran();
                    throw;
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"修改审批流程时发生异常: {ex.Message}");

                return new ApiResult<bool>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"修改失败: {ex.Message}",
                    Data = false
                };
            }
        }


        /// <summary>
        /// 停用审批流程节点主表
        /// </summary>
        /// <param name="processNodes"></param>
        /// <returns>操作结果</returns>
        public ApiResult<bool> UpdateProcessNodesEnable(ProcessNodes processNodes)
        {
            try
            {
                if (string.IsNullOrEmpty(processNodes.ProcessNodesId))
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "流程节点ID不能为空",
                        Data = false
                    };
                }
                
                var approvalProcess = _ApprovalProcess.GetAll().Where(x => x.ProcessNodesId == processNodes.ProcessNodesId && (x.WFStatus == 0 || x.WFStatus == 1))?.ToList();
                if (approvalProcess.Count() > 0)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "还有未完成的审批流程，完成流程后请停用该审批！！！",
                        Data = false
                    };

                }
                // 检查记录是否存在
                var existingNode = _ProcessNodes.GetValue(x => x.ProcessNodesId == processNodes.ProcessNodesId);
                if (existingNode == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = $"未找到ID为 {processNodes.ProcessNodesId} 的流程节点",
                        Data = false
                    };
                }

                // 获取数据库上下文，用于事务处理
                var db = _ProcessNodes.GetAll().Context;

                try
                {
                    // 开始事务
                    db.Ado.BeginTran();
                    var IsEnable = processNodes.IsEnable;
                    //processNodes.IsEnable = IsEnable;
                    var Message = string.Empty;
                    if (IsEnable)
                    {
                        Message = "启用成功";
                    }
                    else
                    {
                        Message = "停用成功";
                    }
                    // 更新审批流程节点主表
                    var mainResult = _ProcessNodes.Update(processNodes);
                    if (mainResult <= 0)
                    {
                        throw new Exception("更新审批流程节点主表失败");
                    }


                    // 提交事务
                    db.Ado.CommitTran();

                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Success,
                        Message = Message,
                        Data = true
                    };
                }
                catch (Exception ex)
                {
                    // 回滚事务
                    db.Ado.RollbackTran();
                    throw;
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"停用审批流程时发生异常: {ex.Message}");

                return new ApiResult<bool>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"停用失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 取消审批流程
        /// </summary>
        /// <param name="approvalProcessId">审批流程ID</param>
        /// <param name="cancelReason">取消原因</param>
        /// <param name="operatorId">操作人ID</param>
        /// <returns>操作结果</returns>
        public ApiResult<bool> CancelApprovalProcess(string approvalProcessId, string cancelReason, string operatorId)
        {
            // 参数验证
            if (string.IsNullOrEmpty(approvalProcessId))
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = "审批流程ID不能为空",
                    Data = false
                };
            }

            // 获取数据库上下文，用于事务处理
            var db = _ApprovalProcess.GetAll().Context;

            try
            {
                // 开始事务
                db.Ado.BeginTran();

                // 检查审批流程是否存在
                var approvalProcess = _ApprovalProcess.GetValue(x => x.ApprovalProcessId == approvalProcessId);
                if (approvalProcess == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = $"未找到ID为 {approvalProcessId} 的审批流程",
                        Data = false
                    };
                }

                // 检查是否可以取消（只有特定状态的审批流程可以取消）
                if (approvalProcess.WFStatus != 0) // 假设"1"为待审批状态
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "当前状态的审批流程不允许取消",
                        Data = false
                    };
                }

                // 更新审批流程状态
                approvalProcess.WFStatus = 5; // 假设"0"为已取消状态
                approvalProcess.UpdateTime = DateTime.Now;
                approvalProcess.Memo = cancelReason;
                var updateResult = _ApprovalProcess.Update(approvalProcess);
                if (updateResult <= 0)
                {
                    throw new Exception("更新审批流程状态失败");
                }

                // 添加审批记录
                var record = new ProcessRecords
                {
                    ProcessRecordsId = YitIdHelper.NextId(),
                    ApprovalProcessId = approvalProcessId,
                    CurrentNodeSn = approvalProcess.NodeSN,
                    CurrentNode = approvalProcess.NodeName,
                    OperatorId = approvalProcess.OperatorId,
                    Operator = approvalProcess.Operator,
                    UpdateTime = DateTime.Now,
                    IsRead = true,
                    Ispass = approvalProcess.WFStatus
                };

                var recordResult = _ProcessRecords.Add(record);
                if (recordResult <= 0)
                {
                    throw new Exception("添加审批记录失败");
                }

                // 提交事务
                db.Ado.CommitTran();

                return new ApiResult<bool>
                {
                    Code = ApiEnums.Success,
                    Message = "取消审批流程成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                db.Ado.RollbackTran();

                Console.WriteLine($"取消审批流程时发生异常: {ex.Message}");
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = $"取消失败: {ex.Message}",
                    Data = false
                };
            }
        }

        #endregion

        #region 删除
        /// <summary>
        /// 删除审批流程节点（包含相关的明细记录）
        /// </summary>
        /// <param name="processNodesId">流程节点ID</param>
        /// <returns>操作结果</returns>
        public ApiResult<bool> DeleteProcessNode(string processNodesId)
        {
            // 参数验证
            if (string.IsNullOrEmpty(processNodesId))
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = "流程节点ID不能为空",
                    Data = false
                };
            }
            // 获取数据库上下文，用于事务处理
            var db = _ProcessNodes.GetAll().Context;

            try
            {
                // 开始事务
                db.Ado.BeginTran();

                // 检查节点是否存在
                var processNode = _ProcessNodes.GetValue(x => x.ProcessNodesId == processNodesId);
                if (processNode == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = $"未找到ID为 {processNodesId} 的流程节点",
                        Data = false
                    };
                }

                // 检查是否有关联的审批流程
                var relatedProcess = _ApprovalProcess.GetAll().Any(x => x.ProcessNodesId == processNodesId);
                if (relatedProcess)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "该流程节点已被审批流程引用，无法删除,请停用后重新新建该审批",
                        Data = false
                    };
                }

                //// 删除相关的明细记录
                //var nodeItems = _ProcessNodesItem.GetAll().Where(x => x.ProcessNodesId == processNodesId).ToList();
                //foreach (var item in nodeItems)
                //{
                //    var itemResult = _ProcessNodesItem.Delete(item);
                //    if (itemResult <= 0)
                //    {
                //        throw new Exception($"删除流程节点明细失败: {item.ProcessNodesItemId}");
                //    }
                //}

                //// 删除主表记录
                //var result = _ProcessNodes.Delete(processNode);
                //if (result <= 0)
                //{
                //    throw new Exception("删除流程节点主表记录失败");
                //}
                processNode.IsDelelte = true;
                // 删除主表记录
                var result = _ProcessNodes.Update(processNode);
                if (result <= 0)
                {
                    throw new Exception("删除流程节点主表记录失败");
                }

                // 提交事务
                db.Ado.CommitTran();

                return new ApiResult<bool>
                {
                    Code = ApiEnums.Success,
                    Message = "删除成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                db.Ado.RollbackTran();

                Console.WriteLine($"删除流程节点时发生异常: {ex.Message}");
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = $"删除失败: {ex.Message}",
                    Data = false
                };
            }
        }
        #endregion

        #region 通过


        /// <summary>
        /// 同意审批流程
        /// </summary>
        /// <param name="approval"></param>
        /// <returns></returns>
        public ApiResult<bool> ApproveProcess(ApprovalProcess approval)
        {
            // 参数验证
            if (string.IsNullOrEmpty(approval.ApprovalProcessId))
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = "审批流程ID不能为空",
                    Data = false
                };
            }

            if (string.IsNullOrEmpty(approval.OperatorId) || string.IsNullOrEmpty(approval.Operator))
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = "操作人信息不能为空",
                    Data = false
                };
            }

            // 获取数据库上下文，用于事务处理
            var db = _ApprovalProcess.GetAll().Context;

            try
            {
                // 开始事务
                db.Ado.BeginTran();

                // 获取当前审批流程信息
                var approvalProcess = _ApprovalProcess.GetValue(x => x.ApprovalProcessId == approval.ApprovalProcessId);
                if (approvalProcess == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = $"未找到ID为 {approval.ApprovalProcessId} 的审批流程",
                        Data = false
                    };
                }

                // 验证当前操作人是否为待办人
                if (approvalProcess.ToDoerId != approval.OperatorId)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "您不是当前审批节点的处理人，无权进行审批操作",
                        Data = false
                    };
                }

                // 获取当前流程节点信息
                var processNodes = _ProcessNodes.GetValue(x => x.ProcessNodesId == approvalProcess.NodeSN);
                if (processNodes == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "未找到对应的流程节点配置",
                        Data = false
                    };
                }

                // 获取当前流程所有节点明细
                var nodeItems = _ProcessNodesItem.GetAll()
                                        .Where(x => x.ProcessNodesId == processNodes.ProcessNodesId)
                                        .OrderBy(x => x.NodeSn)
                                        .ToList();

                // 找到当前节点在流程中的位置
                var currentNodeItem = nodeItems.FirstOrDefault(x => x.ProcessNodesItemId == approvalProcess.NodeSN);
                if (currentNodeItem == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "未找到当前审批节点信息",
                        Data = false
                    };
                }

                // 记录当前审批记录
                var processRecord = new ProcessRecords
                {
                    ProcessRecordsId = YitIdHelper.NextId(),
                    ApprovalProcessId = approval.ApprovalProcessId,
                    CurrentNodeSn = approvalProcess.NodeSN,
                    CurrentNode = approvalProcess.NodeName,
                    OperatorId = approval.OperatorId,
                    Operator = approval.Operator,
                    ApproveOpinion = approval.Memo,
                    UpdateTime = DateTime.Now,
                    IsRead = true,
                    Ispass = approval.WFStatus
                };

                var recordResult = _ProcessRecords.Add(processRecord);
                if (recordResult <= 0)
                {
                    throw new Exception("添加审批记录失败");
                }

                // 查找下一个节点
                int currentIndex = nodeItems.IndexOf(currentNodeItem);
                bool isLastNode = (currentIndex >= nodeItems.Count - 1);

                if (isLastNode)
                {
                    // 当前节点是最后一个节点，流程完成
                    approvalProcess.WFStatus = 4;
                    approvalProcess.OperatorId = approval.OperatorId;
                    approvalProcess.Operator = approval.Operator;
                    approvalProcess.UpdateTime = DateTime.Now;
                    approvalProcess.ToDoerId = "";
                    approvalProcess.ToDoer = "";
                    approvalProcess.Memo = approval.Memo;
                }
                else
                {
                    // 获取下一个节点
                    var nextNodeItem = nodeItems[currentIndex + 1];

                    // 更新审批流程到下一节点
                    approvalProcess.NodeSN = nextNodeItem.ProcessNodesItemId;
                    approvalProcess.NodeName = nextNodeItem.NodeName;
                    approvalProcess.OperatorId = approval.OperatorId;
                    approvalProcess.Operator = approval.Operator;
                    approvalProcess.WFStatus = 1;
                    approvalProcess.UpdateTime = DateTime.Now;
                    approvalProcess.ToDoerId = nextNodeItem.OperatorId; // 设置下一节点的处理人
                    approvalProcess.ToDoer = nextNodeItem.Operator;
                    approvalProcess.Memo = approval.Memo;
                }

                // 更新审批流程
                var updateResult = _ApprovalProcess.Update(approvalProcess);
                if (updateResult <= 0)
                {
                    throw new Exception("更新审批流程失败");
                }

                // 提交事务
                db.Ado.CommitTran();

                return new ApiResult<bool>
                {
                    Code = ApiEnums.Success,
                    Message = isLastNode ? "审批流程已完成" : "审批已通过，流程已进入下一节点",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                db.Ado.RollbackTran();

                Console.WriteLine($"审批流程时发生异常: {ex.Message}");
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = $"审批失败: {ex.Message}",
                    Data = false
                };
            }
        }

        #endregion

        #region 驳回

        /// <summary>
        /// 驳回审批流程
        /// </summary>
        /// <param name="approval"></param>
        /// <returns></returns>
        public ApiResult<bool> RejectProcess(ApprovalProcess approval)
        {
            // 参数验证
            if (string.IsNullOrEmpty(approval.ApprovalProcessId))
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = "审批流程ID不能为空",
                    Data = false
                };
            }

            if (string.IsNullOrEmpty(approval.OperatorId) || string.IsNullOrEmpty(approval.Operator))
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = "操作人信息不能为空",
                    Data = false
                };
            }

            if (string.IsNullOrEmpty(approval.Memo))
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = "驳回理由不能为空",
                    Data = false
                };
            }

            // 获取数据库上下文，用于事务处理
            var db = _ApprovalProcess.GetAll().Context;

            try
            {
                // 开始事务
                db.Ado.BeginTran();

                // 获取当前审批流程信息
                var approvalProcess = _ApprovalProcess.GetValue(x => x.ApprovalProcessId == approval.ApprovalProcessId);
                if (approvalProcess == null)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = $"未找到ID为 {approval.ApprovalProcessId} 的审批流程",
                        Data = false
                    };
                }

                // 验证当前操作人是否为待办人
                if (approvalProcess.ToDoerId != approval.OperatorId)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnums.Fail,
                        Message = "您不是当前审批节点的处理人，无权进行驳回操作",
                        Data = false
                    };
                }

                // 记录当前驳回记录
                var processRecord = new ProcessRecords
                {
                    ProcessRecordsId = YitIdHelper.NextId(),
                    ApprovalProcessId = approval.ApprovalProcessId,
                    CurrentNodeSn = approvalProcess.NodeSN,
                    CurrentNode = approvalProcess.NodeName,
                    OperatorId = approval.OperatorId,
                    Operator = approval.Operator,
                    ApproveOpinion = approval.Memo,
                    UpdateTime = DateTime.Now,
                    IsRead = true,
                    Ispass = 3 // 3表示驳回状态
                };

                var recordResult = _ProcessRecords.Add(processRecord);
                if (recordResult <= 0)
                {
                    throw new Exception("添加驳回记录失败");
                }

                // 更新审批流程状态为驳回
                approvalProcess.WFStatus = 3; // 3表示驳回状态
                approvalProcess.OperatorId = approval.OperatorId;
                approvalProcess.Operator = approval.Operator;
                approvalProcess.UpdateTime = DateTime.Now;
                approvalProcess.ToDoerId = approvalProcess.StarterId; // 驳回至申请人
                approvalProcess.ToDoer = approvalProcess.Starter;
                approvalProcess.Memo = approval.Memo;

                // 更新审批流程
                var updateResult = _ApprovalProcess.Update(approvalProcess);
                if (updateResult <= 0)
                {
                    throw new Exception("更新审批流程失败");
                }

                // 提交事务
                db.Ado.CommitTran();

                return new ApiResult<bool>
                {
                    Code = ApiEnums.Success,
                    Message = "审批已驳回，流程已退回至申请人",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                // 回滚事务
                db.Ado.RollbackTran();

                Console.WriteLine($"驳回审批流程时发生异常: {ex.Message}");
                return new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Message = $"驳回失败: {ex.Message}",
                    Data = false
                };
            }
        }

        #endregion
    }
}
